<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'
import { SearchForm, SearchTable } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import { reactive } from 'vue'
import { useActManageIndex, useActManageDelete, useActManageEnable } from '@fl/api/anjutong/activity-management'
import { type RequestActIndex  } from '@fl/api/anjutong/model/activity-management-model'
import { useDicts } from './hooks/use-dicts'
const { dicts: { ActType, ActStatus }, useDict } = useDicts()
import dataScan from './components/data-scan.vue'
import dataScanCoupon from './components/data-scan-coupon.vue'

defineOptions({
    // eslint-disable-next-line vue/component-definition-name-casing
    name: 'activity-manage-activity-management',
})

const { push } = useRouter()
const tableRef = ref()
const visible = ref<boolean>(false)
const couponVisible = ref<boolean>(false)
const scanId = ref<string>('')
const couponScanId = ref<string>('')

// 搜索条件、分页参数
const initialState = {
    activityName: '',
    activityType: null,
    activityStatus: '',
}
const state = ref<RequestActIndex>(cloneDeep(initialState))

const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}
const tablePage = ref(cloneDeep(initialPage))

// 查询列表
const params = computed(() => ({
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
    ...state.value,
}))
const { data, isLoading } = useActManageIndex(params)
const records = ref<any>()

watchEffect(() => {
    if (data.value) {
        records.value = cloneDeep(data.value.records).reduce((pre, cur) => {
            cur.activityStatus = cur.activityStatus ? String(cur.activityStatus) : '0'
            // cur.formatNumberWithUnit()
            pre.push(cur)
            return pre
        }, [])
        tablePage.value.total = data.value.total!
    }
})

// 删除
const { mutate: deleteMutate } = useActManageDelete()
// 启用禁用
const { mutate: enableMutate } = useActManageEnable()

function switchStatus(row: any) {
    enableMutate(row.id, {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}

// 搜索
function submit(values: RequestActIndex) {
    state.value = { ...values }
    tablePage.value.currentPage = 1
}

// 重置
function reset() {
    state.value = initialState
    tablePage.value = initialPage
}

// 新增
function goToAdd() {
    push({ name: 'activity-manage-activity-add-or-edit' })
}

// 复制链接
function goToCopy(row: any) {
    push({ name: 'activity-manage-activity-add-or-edit', query: { type: 'copy', id: row.id } })
}

// 列表：查看
function goToShow(row: any) {
    if(row.activityType === 2) {
        // 优惠券
        couponVisible.value = true
        couponScanId.value = row.id || ''
    } else {
        // 活动报名
        visible.value = true
        scanId.value = row.id || ''
    }
}

// 列表：编辑
function goToEdit(row: any) {
    push({ name: 'activity-manage-activity-add-or-edit', query: { type: 'edit', id: row.id} })
}

// 列表：删除
function deleteConfirm(row: any) {
    deleteMutate({ id: row.id }, {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

// function formatNumberWithUnit(num) {
//     if (num >= 10000) {
//         return (num / 10000).toFixed(2) + ' 万';
//     }
//     return num;
// }

const columns: PlusColumn[] = [
    {
        label: '活动名称',
        prop: 'activityName',
        valueType: 'copy',
    },
    {
        label: '活动类型',
        prop: 'activityType',
        options: ActType,
        valueType: 'select',
    },
    {
        label: '状态',
        options: ActStatus,
        prop: 'activityStatus',
        valueType: 'select',
    },
]
const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: '序号', type: 'seq', width: 70 },
        { field: 'activityName', title: '活动名称' },
        { field: 'activityType', slots: { default: 'activityType' }, title: '活动类型' },
        { field: 'startTime', title: '活动开始时间' },
        { field: 'endTime', title: '活动结束时间' },
        { field: 'valueAmount', title: '优惠活动价值' },
        { field: 'activityStatus', slots: { default: 'activityStatus' }, title: '状态' },
        { fixed: 'right', slots: { default: 'operate' }, title: '操作', width: 190 },
    ],
})
</script>

<template>
    <ElCard class="mb-20" shadow="never">
        <SearchForm v-bind="state" :columns="columns" submit-text="搜索" @reset="reset" @submit="submit" />
    </ElCard>

    <div>
        <ElCard class="body" shadow="never">
            <SearchTable ref="tableRef" v-bind="gridOptions" v-model:pager="tablePage" :loading="isLoading" :data="records"
                @page-change="handlePageChange">
                
                <template #activityType="{ row }">
                    {{ useDict('ActType', row.activityType) }}
                </template>

                <template #activityStatus="{ row }">
                    <!-- {{ useDict('ActStatus', row.activityStatus) }} -->
                    <el-switch v-model="row.activityStatus" :active-value="'1'" :inactive-value="'0'"  inline-prompt @change="switchStatus(row)" />
                </template>

                <!-- <template #valueAmount="{ row }">
                    {{ formatNumberWithUnit(row.valueAmount) }}
                </template> -->
                
                <template #toolbar_buttons>
                    <ElButton type="primary" @click="goToAdd">
                        <div class="i-ic:baseline-add size-16" />
                        新增
                    </ElButton>
                </template>

                <template #operate="{ row }">
                    <el-button class="small" text @click="goToCopy(row)">
                        复制
                    </el-button>

                    <el-button class="small" text @click="goToShow(row)">
                        数据
                    </el-button>

                    <el-button class="small" type="primary" text @click="goToEdit(row)">
                        编辑
                    </el-button>

                    <el-popconfirm title="确认删除吗？" @confirm="deleteConfirm(row)">
                        <template #reference>
                            <el-button text type="warning" class="small">
                                删除
                            </el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </SearchTable>
        </ElCard>
    </div>
    
    <dataScan v-model:visible="visible" v-model:id="scanId"></dataScan>
    <dataScanCoupon v-model:visible="couponVisible" v-model:id="couponScanId"></dataScanCoupon>
    
</template>

<style lang="scss" scoped>
:deep(.small.el-button) {
    padding: 4px;
    margin-left: 6px;
}
:deep(.el-tabs__nav-wrap::after) {
    display: none;
}
</style>
